package com.zhang.study.chapter08;

import java.util.HashMap;

public class Code02_TrieTreeByMap {

    public static class Node {
        public int pass;
        public int end;
        public HashMap<Integer, Node> nexts;

        public Node() {
            pass = 0;
            end = 0;
            nexts = new HashMap<>();
        }
    }

    public static class Trie {
        private Node root;

        public Trie() {
            root = new Node();
        }

        public void insert(String word) {
            if (word == null) {
                return;
            }
            char[] chars = word.toCharArray();
            Node node = root;
            node.pass++;
            for (char c : chars) {
                if (!node.nexts.containsKey((int) c)) {
                    node.nexts.put((int) c, new Node());
                }
                node = node.nexts.get((int) c);
                node.pass++;
            }
            node.end++;
        }

        public int search(String word) {
            if (word == null) {
                return 0;
            }
            char[] chars = word.toCharArray();
            Node node = root;
            for (char c : chars) {
                if (!node.nexts.containsKey((int) c)) {
                    return 0;
                }
                node = node.nexts.get((int) c);
            }
            return node.end;
        }

        public int prefixNumber(String word) {
            if (word == null) {
                return 0;
            }
            char[] chars = word.toCharArray();
            Node node = root;
            for (char c : chars) {
                if (!node.nexts.containsKey((int) c)) {
                    return 0;
                }
                node = node.nexts.get((int) c);
            }
            return node.pass;
        }

        public void delete(String word) {
            if (search(word) != 0) {
                char[] chars = word.toCharArray();
                Node node = root;
                node.pass--;
                for (char c : chars) {
                    if (--node.nexts.get((int) c).pass == 0) {
                        node.nexts.remove((int) c);
                        return;
                    }
                    node = node.nexts.get((int) c);
                }
                node.end--;
            }
        }

    }


}
